import React, {Component} from 'react';
import {
    Dimensions,
    FlatList,
    Image,
    PixelRatio,
    StyleSheet,
    Text,
    TouchableHighlight,
    View,
    TouchableOpacity,
    ScrollView,
    AsyncStorage,
    DeviceEventEmitter,
    StatusBar,
    Platform
} from 'react-native';


import Util from'../common/Utils'
import {ListRow, SearchInput,Drawer,Theme} from 'teaset';
import Config from '../common/Config'
import Utils from '../Utils'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
import TitleBar from '../views/TitleBar';
import CommonLoadingView from '../views/CommonLoadingView';
export default class AddressBookTabPage extends Component {
    componentDidMount() {
        this.msgListener = DeviceEventEmitter.addListener('refresherHead',(listenerMsg) => {
            this.getContacts();
        });
        this._loadInitialState().done();
    }
    componentWillUnmount() {
        this.msgListener&&this.msgListener.remove();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getContacts());
    };
    constructor(props) {
        super(props);
        this.state = {
            loadingState: 1,
            contactData: null,
            token:'',
            searchMsg:''
        }
    }

    getContacts=()=> {
        let login={
            "token":this.state.token
        };
        fetch(Config.baseApi+'/directories/getList',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Util.getParamsString(login)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    this.setState({
                        loadingState:2,
                        contactData:responseJson.data
                    })
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
        // var url = "http://rnwechat.applinzi.com/friends"; // 新接口
        // fetch(url).then((res) => res.json())
        //     .then((json) => {
        //         UserInfoUtil.setUserInfo(json);
        //         this.setState({
        //             loadingState: 2,
        //             contactData: json
        //         })
        //     })
    }

    render() {
        switch (this.state.loadingState) {
            case 1:
                return this.renderLoadingView();
            case 2:
                return this.renderSuccessView();
            case 3:
                return this.renderErrorView();
            default:
        }
    }

    renderLoadingView=()=> {
        return (
            <View style={styles.container}>
                <TitleBar nav={this.props.navigation}/>
                <View style={styles.content}>
                    <CommonLoadingView hintText={"正在获取联系人数据..."}/>
                </View>
            </View>
        );
    };

    renderErrorView=()=> {
        return (
            <View style={{justifyContent: 'center', alignItems: 'center', flex: 1, flexDirection: 'column'}}>
                <Text style={{fontSize: 16, color: '#000000'}}>加载数据出错！</Text>
            </View>
        );
    }

    renderSuccessView=()=> {
        var listData = [];
        var headerListData = [];
        var headerImages = [ ImageUtil.NewFriend, ImageUtil.GroupChat];
        var headerTitles = ['新的朋友'];
        var index = 0;
        for (let i = 0; i < headerTitles.length; i++) {
            headerListData.push({
                key: index++,
                title: headerTitles[i],
                nick: headerTitles[i],
                icon: headerImages[i],
                sectionStart: false,
            });
        }
        var contacts = this.state.contactData;
        for (let i = 0; i < contacts.length; i++) {
            // var pinyin = PinyinUtil.getFullChars(contacts[i].name);
            var pinyin = contacts[i].pinyin.toUpperCase();
            var firstLetter = pinyin.substring(0, 1);
            if (firstLetter < 'A' || firstLetter > 'Z') {
                firstLetter = '#';
            }
            let icon = ImageUtil.Search;
            if (!Utils.isEmpty(contacts[i].head)) {
                icon = {uri: 'http://106.14.209.177/upload/'+contacts[i].head};
            }
            listData.push({
                key: index++,
                icon: icon,
                title: contacts[i].name,
                nick: contacts[i].remarkName,
                pinyin: pinyin,
                firstLetter: firstLetter,
                id:contacts[i].id,
                sectionStart: false,
                isSelect:false
            })
        }
        // 按拼音排序
        listData.sort(function (a, b) {
            if (a.pinyin === undefined || b.pinyin === undefined) {
                return 1;
            }
            if (a.pinyin > b.pinyin) {
                return 1;
            }
            if (a.pinyin < b.pinyin) {
                return -1;
            }
            return 0;
        });
        listData = headerListData.concat(listData);
        // 根据首字母分区
        for (var i = 0; i < listData.length; i++) {
            var obj = listData[i];
            if (obj.pinyin === undefined) {
                continue;
            }
            if (i > 0 && i < listData.length) {
                var preObj = listData[i - 1];
                if (preObj.pinyin === undefined && obj.pinyin !== undefined) {
                    obj.sectionStart = true;
                } else if (preObj.pinyin !== undefined && obj.pinyin !== undefined && preObj.firstLetter !== obj.firstLetter) {
                    obj.sectionStart = true;
                }
            }
            let select=listData[i-1];
            if(select.sectionStart==true||select.sectionStart==false){
                if(select.firstLetter==listData[i].firstLetter){
                    listData[i-1].isSelect=true
                }
            }
        }
        this.listData = listData;
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="black"
                    barStyle="light-content"
                />
                {alert(JSON.stringify(listData))}
                <View style={styles.titleView}>
                    <Text style={styles.titleMsg}>通讯录</Text>
                    <TouchableOpacity
                        onPress={()=>Actions.AddFriendPage()}
                        style={styles.titleImgView}>
                        <Image
                            style={styles.titleImg}
                            source={ImageUtil.AddFriend}/>
                    </TouchableOpacity>
                </View>
                <View style={styles.content}>
                    <FlatList
                        ref={'list'}
                        data={listData}
                        renderItem={this._renderItem}
                        ListHeaderComponent={this.ListHeader}
                        getItemLayout={this._getItemLayout}
                    />
                    {/*<SideBar onLetterSelectedListener={this.onSideBarSelected.bind(this)}/>*/}
                </View>
                <View style={styles.divider}/>
            </View>
        );
    };

    searching=()=>{
        let login={
            "token":this.state.token,
            "content":this.state.searchMsg
        };
        fetch(Config.baseApi+'/directories/searchFriend',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Util.getParamsString(login)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){

                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    ListHeader=()=>{
        return(
            <View>
                <TouchableOpacity
                    onPress={()=>Actions.FindFriendPage()}
                    style={{justifyContent:'center',alignItems:'center'}}>
                    <View style={styles.searchInput}>
                        <Image source={ImageUtil.Search}/>
                        <Text style={{fontSize:14,color:'#646464',marginLeft:12}}>搜索</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity style={styles.labelView}>
                    <Image
                        style={styles.labelImg}
                        source={ImageUtil.CustomerService}/>
                    <Text style={styles.labelMsg}>信用客服0574</Text>
                </TouchableOpacity>
                <View style={{height:12,width:width}}/>
            </View>
        )
    };

    _getItemLayout = (data, index) => {
        let len = data.sectionStart ? (58) : (51);
        let dividerHeight = 1 / PixelRatio.get();
        return {
            length: len,
            offset: (len + dividerHeight) * index,
            index
        };
    }

    onSideBarSelected=(letter)=> {
        if (this.listData) {
            for (let i = 0; i < this.listData.length; i++) {
                let item = this.listData[i];
                if (item.firstLetter == letter && item.sectionStart) {
                    Toast.message(letter);
                    this.refs.list.scrollToIndex({viewPosition: 0, index: i});
                    break;
                }
            }
        }
    }

    onListItemClick=(item)=> {
        let index = item.item.key;
        if (index == 0) {
            // 新的朋友
            Actions.NewFriendPage({data: item.item})
        } else {
            Actions.DetailsPage({id:item.item.id});
        }
    }

    _renderItem = (item) => {
        var section = [];
        if (item.item.sectionStart) {
            section.push(<View
                style={{borderBottomWidth:0}}
                key={"section" + item.item.key}>
                <Text style={listItemStyle.sectionView}>{item.item.firstLetter}</Text>
            </View>);
        }
        return (
            <View >
                {section}
                <TouchableHighlight
                    onPress={() => {
                        this.onListItemClick(item)
                    }}>
                    <View style={listItemStyle.container} key={item.item.key}>
                        <View style={{width:width-30,marginLeft:15,flexDirection:'row', alignItems: 'center',}}>
                            <Image style={listItemStyle.image} source={item.item.icon}/>
                            {item.item.nick!==null&&item.item.nick!=''
                            ?(<Text style={listItemStyle.itemText}>{item.item.nick}</Text>)
                            :(<Text style={listItemStyle.itemText}>{item.item.title}</Text>)}
                            <Text style={listItemStyle.subText}>{Utils.isEmpty(item.item.nick)}</Text>
                        </View>
                    </View>
                </TouchableHighlight>
                {item.item.isSelect
                    ?(<View style={{height:1,width:width,backgroundColor:'#ffffff'}}>
                        <View style={{height:1,width:width-15,marginLeft:15,backgroundColor:'#e3e3e4'}}/>
                    </View>)
                    :null}
            </View>
        );
    }
}

const listItemStyle = StyleSheet.create({
    container: {
        width: width,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#ffffff',

    },
    image: {
        marginRight: 19,
        marginTop: 5,
        marginBottom: 5,
        width: 35,
        height: 35,
    },
    itemText: {
        fontSize: 15,
        color: '#000000'
    },
    subText: {
        fontSize: 15,
        color: '#999999'
    },
    sectionView: {
        width: width-30,
        backgroundColor: 'rgba(0, 0, 0, 0)',
        marginLeft: 15,
        color: '#000000',
    }
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor:'#f0f0f0'
    },
    divider: {
        width: width,
        height: 1 / PixelRatio.get(),
        backgroundColor: '#D3D3D3'
    },
    content: {
        flex: 1,
        width: width,
        flexDirection: 'row',
        backgroundColor: '#f0f0f0'
    },
    tabBarIcon: {
        width: 24,
        height: 24,
    },
    labelView:{
        height:45,
        width:width,
        backgroundColor:'#ffffff',
        marginTop:12,
        flexDirection:'row',
        alignItems:'center'
    },
    labelChangeView:{
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:12,
        alignItems:'center'
    },
    labelImg:{
        marginLeft:15,
        width:30,
        height:30,
        borderRadius:5
    },
    labelMsg:{
        marginLeft:19,
        fontSize:14,
        color:'#000000'
    },
    labelCategorizeView:{
        borderBottomWidth:1,
        borderColor:'#e3e3e4',
        width:width-30,
        flexDirection:'row',
        alignItems:'center',
        height:45
    },
    labelCategorizeImg:{
        width:30,
        height:30,
        borderRadius:5
    },
    labelCategorizeViewBottom:{
        width:width-30,
        flexDirection:'row',
        alignItems:'center',
        height:45
    },
    iconView:{
        height:17,
        justifyContent:'center',
        width:width,
    },
    iconMsg:{
        fontSize:14,
        color:'#000000',
        marginLeft:15
    },
    labelChange:{
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        alignItems:'center'
    },
    searchInput:{
        width:width-30,
        height:29,
        borderWidth:1,
        borderColor:'#e3e3e4',
        marginTop:12,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:5,
        backgroundColor:'#ffffff'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44
    },
    titleMsg:{
        textAlign:'center',
        fontSize:20,
        color:'#ffffff',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    titleImg:{
        height:20,
        width:20
    },
    titleImgView:{
        position:'absolute',
        bottom:27/2,right:15
    },
});

